package com.site.base.dao;

/**
 * 版权所有 违者必究
 * by chenxh
 */

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;


/**
 * <br><b>类描述:</b>
 * <br>所有DAO的基类
 *
 * @since 1.0
 */
public class BaseJdbcDao {
    
    protected Log log = (Log) LogFactory.getLog(this.getClass());
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private SimpleJdbcTemplate simpleJdbcTemplate;
    
    @Autowired
    private SimpleJdbcInsert simpleJdbcInsert;
    
    /*日志记录器*/
    protected Log logger = LogFactory.getLog(this.getClass());

    public final JdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }

    public final SimpleJdbcTemplate getSimpleJdbcTemplate() {
        return this.simpleJdbcTemplate;
    }

    public SimpleJdbcInsert getSimpleJdbcInsert() {
        return simpleJdbcInsert;
    }

    /**
     * 查询单个对象的值，由于直接调用spring的queryForObject，如果记录不存在的话，会抛出异常，为了避免异常出现，因此在基类加了该方法
     * add by chenmk 2008.10.13
     *
     * @param <T>
     * @param sql
     * @param rm
     * @param args
     * @return
     */
    public <T> T queryForObject(String sql, RowMapper<T> rm, Object... args) {

        List<T> queryList = getSimpleJdbcTemplate().query(sql, rm, args);

        if (queryList == null || queryList.size() < 1)
            return null;

        return queryList.get(0);
    }

    /**
     * 判断列名是否存在
     * add by chenmk 2008.09.05
     *
     * @param rs
     * @param columnName
     * @return
     * @throws SQLException
     */
    public boolean isExsitedColumn(ResultSet rs, String columnName) throws SQLException {

        if (rs == null || StringUtils.isEmpty(columnName))
            return false;

        int columnCount = rs.getMetaData().getColumnCount();

        for (int i = 1; i <= columnCount; i++) {
            if (columnName.equalsIgnoreCase(rs.getMetaData().getColumnName(i)))
                return true;
        }
        return false;
    }
}
